package example.simple_mindmap.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import example.simple_mindmap.common.config.RedisProperties;
import example.simple_mindmap.common.domain.dto.MessageDTO;
import example.simple_mindmap.common.domain.dto.UserDTO;
import example.simple_mindmap.common.domain.po.Result;
import example.simple_mindmap.common.enums.ResultCode;
import example.simple_mindmap.common.utils.DataUtil;
import example.simple_mindmap.common.utils.SessionHolder;
import example.simple_mindmap.config.MessageProperties;
import example.simple_mindmap.domain.po.Message;
import example.simple_mindmap.domain.po.User;
import example.simple_mindmap.mapper.MessageMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
@Slf4j
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {
    private final MessageMapper messageMapper;
    private final MessageProperties messageProperties;
    private final UserServiceImpl userService;
    private final RedisProperties redisProperties;


    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 发送消息
     * @Describe: TODO
     **/
    public Result sendMessage(Message message){
        //参数检验
        if(message == null
                || StrUtil.isBlank(message.getContent())
                || DataUtil.isNaturalNumInvalid(message.getRid())){
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //添加文章到数据库
        initialize(message);
        save(message);
        //返回结果给前端
        return Result.success();
    }


    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 获取所有消息
     * @Describe: TODO
     **/
    public Result getAllMessage(){
        List<Message> messageList = messageMapper.selectMessageByRid(SessionHolder.getUser());
        boolean hasUnread = false;
        //判断是否有未读和过期的消息
        for(int i = 0; i < messageList.size(); i++){
            Message message = messageList.get(i);
            if(!hasUnread){
                if(message.getState() == 0){
                    hasUnread = true;
                }
            }
            if(message.getState() == 1 ){
                if(isOutTime(message.getCreateTime())){
                    messageList.remove(i);
                    removeById(message.getId());
                }
            }
        }
        List<MessageDTO> messageDTOS = BeanUtil.copyToList(messageList, MessageDTO.class);
        for(MessageDTO messageDTO : messageDTOS){
            UserDTO userDTO = getUser(messageDTO.getPid());
            if(userDTO == null){
                messageDTO.setPname(redisProperties.default_name);
                messageDTO.setAvatar(redisProperties.default_avatar);
            }else {
                messageDTO.setPname(userDTO.getNickname());
                messageDTO.setAvatar(userDTO.getAvatarUrl());
            }
        }

        Map<String,Object> retMap = new HashMap<>();
        retMap.put("messageList",messageDTOS);
        retMap.put("hasUnread",hasUnread);
        return Result.success(retMap);
    }


    private UserDTO getUser(Long uid){
        User user = userService.getById(uid);
        if(user == null){
            return null;
        }
        UserDTO userDTO = BeanUtil.toBean(user, UserDTO.class);
        return userDTO;
    }

    private Boolean isOutTime(Date time){
        // 创建一个 Calendar 对象，并设置为当前日期
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());

        // 将日期往前推(一周)
        calendar.add(Calendar.DAY_OF_MONTH, -messageProperties.getMessage_outTime_day());

        // 获取一周前的时间戳
        Date oneWeekAgo = calendar.getTime();
        return time.after(oneWeekAgo);
    }

    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 已读消息
     * @Describe: TODO
     **/
     public Result readMessage(Long id) {
         if(DataUtil.isNaturalNumInvalid(id)){
             return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
         }
         lambdaUpdate().eq(Message::getId, id).set(Message::getState, (short) 1).update();
         return Result.success();
    }

    /* ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 初始化
     * @Describe: TODO
     **/
     private void initialize(Message message){
        if(message == null
                || message.getPid() == null
                || message.getRid() == null){

        }
         if(message.getPid() == null){
             message.setPid(SessionHolder.getUser());
         }
        if(message.getContent() == null){
            message.setContent("");
        }
        if(message.getState() == null){
            message.setState((short) 0);
        }
        if(message.getType() == null){
             message.setType((short) 0);
         }
        if(message.getCreateTime() == null){
            message.setCreateTime(new Date());
        }

    }


}
